package x.ovo.wechat.bot.common.plugin.config;

import lombok.Cleanup;
import lombok.SneakyThrows;
import org.yaml.snakeyaml.DumperOptions;
import org.yaml.snakeyaml.Yaml;

import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.Map;

/**
 * YAML 配置
 *
 * @author ovo, created by 2024/05/02
 */
public class YamlConfiguration extends BaseConfigurationSection {

    /**
     * 加载配置
     *
     * @param file 文件
     * @return {@link YamlConfiguration }
     */
    @SneakyThrows
    public static YamlConfiguration loadConfiguration(File file) {
        YamlConfiguration config = new YamlConfiguration();
        Yaml yaml = new Yaml();
        @Cleanup FileReader reader = new FileReader(file);
        config.data = yaml.load(reader);
        return config;
    }

    @Override
    @SuppressWarnings("unchecked")
    public ConfigurationSection getConfigurationSection(String path) {
        String[] keys = path.split("\\.");
        Map<String, Object> current = super.data;

        for (String key : keys) {
            Object value = current.get(key);
            if (value instanceof Map) {
                current = (Map<String, Object>) value;
            } else {
                return null; // 如果路径中的任何部分不是 Map，则返回 null
            }
        }
        YamlConfiguration section = new YamlConfiguration();
        section.data = current;
        return section;
    }

    /**
     * 保存配置
     *
     * @param file 文件
     */
    @SneakyThrows
    public void save(File file) {
        DumperOptions options = new DumperOptions();
        options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
        Yaml yaml = new Yaml(options);
        @Cleanup FileWriter writer = new FileWriter(file);
        yaml.dump(data, writer);
    }
}
